//
//  ArticleListViewController.swift
//  WanAndroidLearn
//
//  Created by TRS-Mobile on 2023/11/1.
//

import UIKit
import ReactorKit
import RxTheme
import KafkaRefresh

class ArticleListViewController: TableViewController, View {
    
    typealias Reactor = ArticleListReactor

    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "文章列表"
        self.reactor = ArticleListReactor()
    }
    
    override func makeUI() {
        super.makeUI()
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        tableView.register(cellWithClass: ArticleCell.self)
    }
    
    func bind(reactor: ArticleListReactor) {
        
        self.rx.viewWillAppear
            .map { _ in ArticleListReactor.Action.refresh }
            .bind(to: reactor.action)
            .disposed(by: disposeBag)
         
        headerRefreshTrigger
            .map { ArticleListReactor.Action.refresh }
            .bind(to: reactor.action)
            .disposed(by: disposeBag)
        
        footerRefreshTrigger
            .map { ArticleListReactor.Action.loadMore }
            .bind(to: reactor.action)
            .disposed(by: disposeBag)
        
        reactor.state
            .map {
                $0.items
            }
            .asDriver(onErrorJustReturn: [])
            .drive(tableView.rx
                .items(cellIdentifier: "ArticleCell", cellType: ArticleCell.self))  { idx, cellReactor, cell in
                    cell.bind(reactor: cellReactor)
                }
                .disposed(by: disposeBag)
        
        reactor.state
            .map { $0.isRefreshing }
            .bind(to: tableView.headRefreshControl.rx.isAnimating)
            .disposed(by: disposeBag)
        reactor.state
            .map { $0.isLoading }
            .bind(to: tableView.footRefreshControl.rx.isAnimating)
            .disposed(by: disposeBag)
    }

}
